package vip.aster.generator.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import vip.aster.common.exception.BusinessException;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

/**
 * 模板工具类
 *
 * @author Aster
 * @since 2024/2/23 15:45
 */
@Slf4j
public class TemplateUtils {
    private static final String FILE_SEPARATOR = StrUtil.SLASH;
    private static final String FILE_BACKSLASH = StrUtil.BACKSLASH;
    private static final String FILE_REGEX = "^[a-zA-Z]:.*$";
    private static final String DEFAULT_TEXT_ENCODING = CharsetUtil.UTF_8;
    private static final String DEFAULT_TEMPLATE_NAME = "templateName";


    /**
     * 获取模板渲染后的内容
     *
     * @param content   模板内容
     * @param dataModel 数据模型
     */
    public static String getContent(String content, Map<String, Object> dataModel) {
        if (dataModel.isEmpty()) {
            return content;
        }

        StringReader reader = new StringReader(content);
        StringWriter sw = new StringWriter();
        try {
            // 渲染模板
            String templateName = dataModel.get(DEFAULT_TEMPLATE_NAME).toString();
            Template template = new Template(templateName, reader, null, DEFAULT_TEXT_ENCODING);
            template.process(dataModel, sw);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("渲染模板失败，请检查模板语法", e);
        }

        content = sw.toString();

        IoUtil.close(reader);
        IoUtil.close(sw);

        return content;
    }

    /**
     * 去除盘符
     * 若首字符为'\'或'/'则去除
     * @param path zip压缩路径
     * @return 路径
     */
    public static String getPath(String path) {
        if (StrUtil.isBlank(path) || path.length() < 4) {
            return path;
        }
        String filePath = path.matches(FILE_REGEX) ? path.substring(3) : path;
        if (FILE_SEPARATOR.equals(String.valueOf(filePath.charAt(0))) || FILE_BACKSLASH.equals(String.valueOf(filePath.charAt(0)))) {
            filePath = filePath.substring(1);
        }
        return filePath;
    }
}
